package com.tedu.charging.service.device;



import com.tedu.charging.service.device.constant.RedisConstants;
import com.tedu.charging.service.device.dao.GunInfoMapper;
import com.tedu.charging.service.device.pojo.po.ChargingStationPO;
import com.tedu.charging.service.device.pojo.po.GunInfoPO;
import com.tedu.charging.service.device.pojo.vo.ChargingStationVO;
import com.tedu.charging.service.device.service.IChargingStationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;

@Component
public class RedisInit {

    @Autowired
    IChargingStationService chargingStationService;

   @Autowired
    GunInfoMapper gunInfoMapper;

    @Autowired
    RedisTemplate redisTemplate;
    @PostConstruct //在tomcat启动时自动运行
    public void readStationWriteToRedis(){
        System.out.println(" run readStationWriteToRedis");
        //1,读数据库中所有充电站
        //参数null表示查询条件。查询条件是null是没有条件，查询表中所有数据
        List<ChargingStationPO> chargingStationPOList = chargingStationService.selectChargingStationList();
        //2,把充电站信息写入redis
        //2.1 创建放位置信息的map集合
        HashMap<String, Point> map = new HashMap<>();

        //3.1 创建操作hash的对象
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(RedisConstants.STATION_DETAIL_HASH);

        //2.2 遍历chargingStationList
        for (ChargingStationPO chargingStationPO : chargingStationPOList) {
            //2.3 得到充电站的经度，纬度
            double longitude=Double.parseDouble(chargingStationPO.getStationLng().toString());
            double  latitude=Double.parseDouble(chargingStationPO.getStationLat().toString());
            //2.4 创建point
            Point point = new Point(longitude, latitude);
            //2.5 得到充电站的id
            String id= chargingStationPO.getId().toString();
            //2.6 把充电站信息放到map中
            map.put(id,point);

            //3.2 把一个充电站信息放到hash中
            ChargingStationVO chargingStationVO = new ChargingStationVO();
            BeanUtils.copyProperties(chargingStationPO,chargingStationVO);
            List<GunInfoPO> gunInfoPOList = gunInfoMapper.selectByStationId(chargingStationPO.getId());
            chargingStationVO.setGunInfoPOList(gunInfoPOList);

            boundHashOperations.put(id, chargingStationVO);
        }
        //2.7 把map中的多个数据一次写入redis,批处理
        BoundGeoOperations boundGeoOperations = redisTemplate.boundGeoOps(RedisConstants.STATION_GEO_ZSET);
        boundGeoOperations.add(map);

    }
}
